import logging.handlers
import asyncore
import sys
import os
from server import Server
from serverconfig import ServerConfig
from connectermanager import ConnecterManager
from scheduler import Scheduler
from clientmanager import ClientManager
import db.manager
import datetime
import servertime
import rpcserver
from taskresult.processor import Processor
from taskflow.taskflowmanager import TaskFlowManager

LOGGINGCFG = 'logging.cfg'

class AutomationServer():
    def __init__(self):
        self.server = Server()
        self.config = ServerConfig()
        self.resultprocessor = Processor(self.config)
        self.db_manager = db.manager.Manager()
        self.connecter_manager = ConnecterManager()
        self.client_manager = ClientManager(self.config, self.connecter_manager, self.db_manager)
        self.scheduler = Scheduler(self.config, self.client_manager, self.connecter_manager, self.db_manager, self.resultprocessor)
        # Add-TaskFlow
        self.taskflow_manager = TaskFlowManager(self.scheduler, self.db_manager, self.resultprocessor)
        self.rpcserver = rpcserver.RpcServer(self)
        
    def Init(self):
        try:
            if not os.path.exists('log'):
                os.mkdir('log')
            if os.path.exists(LOGGINGCFG):
                logging.config.fileConfig(LOGGINGCFG)
            else:
                handler = logging.handlers.TimedRotatingFileHandler('log/automationserver.log', "midnight", 1)
                handler.setFormatter(logging.Formatter('%(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s', '%b%d %H:%M:%S'))
                logging.root.addHandler(handler)
            console = logging.StreamHandler(sys.stdout)
            console.setLevel(logging.DEBUG)
            console.setFormatter(logging.Formatter('%(filename)s %(lineno)d %(levelname)s %(message)s'))
            logging.getLogger().addHandler(console)
            logging.getLogger().setLevel(logging.DEBUG)
        
            self.config.Load('automationserver.cfg')
            
            self.db_manager.Init(self.config.sql_connecter)
            
            self.scheduler.Init()
            
            self.rpcserver.Init()
            
            self.server.bind(('', self.config.port))
            self.server.listen(5)
            
            self.client_manager.Init()
            
            self.resultprocessor.Init()
            
            self.db_manager.Start()
            
            self.resultprocessor.Start()
            
            #Add taks-flow
            self.taskflow_manager.Init()
            
        except Exception as e:
            logging.exception(e)
            return False
        
        logging.info('automationserver init success')
        return True
            
    def Loop(self):
        servertime.current_time = datetime.datetime.now()
        asyncore.loop(timeout=0, use_poll=True, count=1)
        
        for v in self.server.get_connecter():
            self.connecter_manager.AddConnect(v)
            
        self.connecter_manager.Loop()
        
        self.scheduler.Loop()
        
        # Add task-flow
        self.taskflow_manager.Loop()
        
        self.db_manager.Loop()
        
        self.rpcserver.Loop()
        
        
    def Uninit(self):
        self.rpcserver.Uninit()
        
        self.server.close()
        
        self.scheduler.Uninit()
        
        self.db_manager.Uninit()
            
        self.resultprocessor.Uninit()
